Security News
npm Updates Search Experience with New Objective Sorting Options
npm has a revamped search experience with new, more transparent sorting options—Relevance, Downloads, Dependents, and Publish Date.
graphql-query-complexity
Advanced tools
The graphql-query-complexity package is a tool for analyzing and limiting the complexity of GraphQL queries. It helps in preventing abuse by ensuring that queries do not exceed a specified complexity threshold, which can be crucial for maintaining the performance and security of a GraphQL API.
Complexity Analysis
This feature allows you to calculate the complexity of a given GraphQL query. The code sample demonstrates how to use the `getComplexity` function along with a simple estimator to determine the complexity of a basic query.
const { getComplexity, simpleEstimator } = require('graphql-query-complexity');
const { graphql, buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const query = '{ hello }';
const complexity = getComplexity({
schema,
query,
estimators: [
simpleEstimator({ defaultComplexity: 1 })
]
});
console.log('Query Complexity:', complexity);
Complexity Limiting
This feature allows you to enforce a maximum complexity limit on GraphQL queries. The code sample shows how to calculate the complexity of a query and throw an error if it exceeds a predefined maximum complexity.
const { getComplexity, simpleEstimator } = require('graphql-query-complexity');
const { graphql, buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const query = '{ hello }';
const complexity = getComplexity({
schema,
query,
estimators: [
simpleEstimator({ defaultComplexity: 1 })
]
});
const maxComplexity = 10;
if (complexity > maxComplexity) {
throw new Error(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
}
console.log('Query is within the allowed complexity range.');
The graphql-depth-limit package provides a way to limit the depth of GraphQL queries. While graphql-query-complexity focuses on the overall complexity of a query, graphql-depth-limit specifically targets the depth of nested queries. This can be useful for preventing deeply nested queries that could potentially cause performance issues.
The graphql-cost-analysis package is another tool for analyzing the cost of GraphQL queries. It allows you to define custom cost rules and calculate the cost of a query based on those rules. Compared to graphql-query-complexity, graphql-cost-analysis offers more flexibility in defining what constitutes the 'cost' of a query.
This library provides GraphQL query analysis to reject complex queries to your GraphQL server. This can be used to protect your GraphQL servers against resource exhaustion and DoS attacks.
Works with graphql-js reference implementation.
Install the package via npm
npm install -S graphql-query-complexity
Create the rule with a maximum query complexity:
import queryComplexity, {
simpleEstimator
} from 'graphql-query-complexity';
const rule = queryComplexity({
// The maximum allowed query complexity, queries above this threshold will be rejected
maximumComplexity: 1000,
// The query variables. This is needed because the variables are not available
// in the visitor of the graphql-js library
variables: {},
// specify operation name only when pass multi-operation documents
operationName?: string,
// Optional callback function to retrieve the determined query complexity
// Will be invoked whether the query is rejected or not
// This can be used for logging or to implement rate limiting
onComplete: (complexity: number) => {console.log('Determined query complexity: ', complexity)},
// Optional function to create a custom error
createError: (max: number, actual: number) => {
return new GraphQLError(`Query is too complex: ${actual}. Maximum allowed complexity: ${max}`);
},
// Add any number of estimators. The estimators are invoked in order, the first
// numeric value that is being returned by an estimator is used as the field complexity.
// If no estimator returns a value, an exception is raised.
estimators: [
// Add more estimators here...
// This will assign each field a complexity of 1 if no other estimator
// returned a value.
simpleEstimator({
defaultComplexity: 1
})
]
});
The complexity calculation of a GraphQL query can be customized with so called complexity estimators. A complexity estimator is a simple function that calculates the complexity for a field. You can add any number of complexity estimators to the rule, which are then executed one after another. The first estimator that returns a numeric complexity value determines the complexity for that field.
At least one estimator has to return a complexity value, otherwise an exception is raised. You can for example use the simpleEstimator as the last estimator in your chain to define a default value.
You can use any of the available estimators to calculate the complexity of a field or write your own:
simpleEstimator
: The simple estimator returns a fixed complexity for each field. Can be used as
last estimator in the chain for a default value.directiveEstimator
: Set the complexity via a directive in your
schema definition (for example via GraphQL SDL)fieldExtensionsEstimator
: The field extensions estimator lets you set a numeric value or a custom estimator
function in the field config extensions of your schema.Consult the documentation of each estimator for information about how to use them.
An estimator has the following function signature:
type ComplexityEstimatorArgs = {
// The composite type (interface, object, union) that the evaluated field belongs to
type: GraphQLCompositeType,
// The GraphQLField that is being evaluated
field: GraphQLField<any, any>,
// The input arguments of the field
args: {[key: string]: any},
// The complexity of all child selections for that field
childComplexity: number
}
type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number | void;
To use the query complexity analysis validation rule with express-graphql, use something like the following:
import queryComplexity from 'graphql-query-complexity';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import schema from './schema';
const app = express();
app.use('/api', graphqlHTTP(async (request, response, {variables}) => ({
schema,
validationRules: [
queryComplexity({
estimators: [
// Configure your estimators
simpleEstimator({defaultComplexity: 1})
],
maximumComplexity: 1000,
variables,
onComplete: (complexity: number) => {console.log('Query Complexity:', complexity);},
})
]
})));
If you want to calculate the complexity of a GraphQL query outside of the validation phase, for example to
return the complexity value in a resolver, you can calculate the complexity via getComplexity
:
import { getComplexity, simpleEstimator } from 'graphql-query-complexity';
import { parse } from 'graphql';
// Import your schema or get it form the info object in your resolver
import schema from './schema';
// You can also use gql template tag to get the parsed query
const query = parse(`
query Q($count: Int) {
some_value
some_list(count: $count) {
some_child_value
}
}
`);
const complexity = getComplexity({
estimators: [
simpleEstimator({defaultComplexity: 1})
],
schema,
query,
variables: {
count: 10,
},
});
console.log(complexity); // Output: 3
This project is inspired by the following prior projects:
FAQs
Validation rule for GraphQL query complexity analysis
The npm package graphql-query-complexity receives a total of 224,732 weekly downloads. As such, graphql-query-complexity popularity was classified as popular.
We found that graphql-query-complexity demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm has a revamped search experience with new, more transparent sorting options—Relevance, Downloads, Dependents, and Publish Date.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.